package com.andy.nature.vm

import com.andy.common.base.BaseViewModel
import com.andy.logcat.LogUtils
import com.andy.nature.model.User
import com.andy.toast.utils.ToastUtils
import com.squareup.moshi.Moshi
import fromJson
import toJson

/**
 * Author:Andy
 * Date:2023/3/20 16:19
 * Description:StrangersViewModel
 */
class ToolViewModel : BaseViewModel() {
    /**
     * 转换成数据model
     */
    fun convertJson2Model(): User? {
        val json = "{\"address\":\"上海市长宁区\",\"age\":\"18\",\"name\":\"张三\",\"phone\":\"18114488517\"}"
        val item = json.fromJson<User>()
        LogUtils.e("Ancoding", "item====${item?.toJson()}")
        ToastUtils.success(item?.toJson() ?: "")
        return item
    }

    /**
     * 转换成Json字符串
     */
    fun convertModel2Json(): String {
        val item = User()
        item.name = "张三"
        item.age = "18"
        item.phone = "18114488517"
        item.address = "上海市长宁区"
        val json = item.toJson()
        LogUtils.e("Ancoding", "json====${json}")
        ToastUtils.success(json)
        return json
    }

    /**
     * 转换成数据model
     */
    fun convertJson2Map(): Map<String, User>? {
        val json = "{\"0\":{\"address\":\"上海市长宁区\",\"age\":\"18\",\"name\":\"张三\",\"phone\":\"18114488517\"},\"1\":{\"address\":\"上海市长宁区\",\"age\":\"19\",\"name\":\"李四\",\"phone\":\"18114488518\"}}"
        val moshi = Moshi.Builder().build()
        val adapter = moshi.adapter<Map<String, User>>(Map::class.java)
        val map = adapter.fromJson(json)
        LogUtils.e("Ancoding", "item====${map?.toJson()}")
        ToastUtils.success(map?.toJson() ?: "")
        return map
    }

    /**
     * 转换成Json字符串
     */
    fun convertMap2Json(): String {
        val user1 = User()
        user1.name = "张三"
        user1.age = "18"
        user1.phone = "18114488517"
        user1.address = "上海市长宁区"
        val user2 = User()
        user2.name = "李四"
        user2.age = "19"
        user2.phone = "18114488518"
        user2.address = "上海市长宁区"
        val userMap = HashMap<Int, User>()
        userMap[0] = user1
        userMap[1] = user2
        val json = userMap.toJson()
        LogUtils.e("Ancoding", "json====${json}")
        ToastUtils.success(json)
        return json
    }
}